package com.nf.xiaomi.dao.impl;

import com.nf.dbutils.SqlExecutor;
import com.nf.dbutils.handlers.BeanListHandler;
import com.nf.xiaomi.dao.AddressDao;
import com.nf.xiaomi.entity.AddressEntity;
import com.nf.xiaomi.util.SqlExecutorUtils;

import java.util.List;

public class AddressDaoImpl implements AddressDao {
    SqlExecutor executor = SqlExecutorUtils.getExecutor();
    @Override
    public List<AddressEntity> getAll() {
        String sql = "select a.address_id,a.user_name,ui.user_account,a.address_content,a.user_phone,a.nstate  from address a\n" +
                "    join user_info ui on ui.user_id = a.user_id";
        BeanListHandler<AddressEntity> handler = new BeanListHandler<>(AddressEntity.class);
        return executor.query(sql, handler);
    }

    @Override
    public List<AddressEntity> getAll(Integer userID) {
        String sql = "select a.address_id,a.user_name,ui.user_account,a.address_content,a.user_phone,a.nstate  from address a\n" +
                "    join user_info ui on ui.user_id = a.user_id where a.user_id = ?";
        BeanListHandler<AddressEntity> handler = new BeanListHandler<>(AddressEntity.class);
        return executor.query(sql, handler,userID);
    }

    @Override
    public List<AddressEntity> getAllAddress(Integer address) {
        String sql = "select a.address_id,a.user_name,ui.user_account,a.address_content,a.user_phone,a.nstate  from address a\n" +
                "    join user_info ui on ui.user_id = a.user_id where a.address_id = ?";
        BeanListHandler<AddressEntity> handler = new BeanListHandler<>(AddressEntity.class);
        return executor.query(sql, handler,address);
    }

    @Override
    public int insert(AddressEntity addressEntity) {
        String sql = "insert into address(user_id,user_name,user_phone,address_content,nstate) values(?,?,?,?,?);";
        return executor.update(sql, addressEntity.getUserId(),addressEntity.getUserName(),addressEntity.getUserPhone(),addressEntity.getAddressContent(),addressEntity.getState());
    }

    @Override
    public int update(AddressEntity addressEntity) {
        String sql = "update address set user_name = ? , user_phone = ?,address_content =?,nstate = ? where address_id = ?";
        return executor.update(sql, addressEntity.getUserName(),addressEntity.getUserPhone(),addressEntity.getAddressContent(),addressEntity.getState(),addressEntity.getAddressId());
    }

    @Override
    public int delete(Integer addressId) {
        String sql = "delete from address where address_id=?";
        return executor.update(sql, addressId);
    }
}
